import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.media.*;
import javax.media.format.AudioFormat;
import javax.media.protocol.ContentDescriptor;
import javax.media.protocol.DataSource;
import javax.sound.sampled.AudioFileFormat;

import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;
import com.sun.speech.freetts.audio.SingleFileAudioPlayer;

public class WavManager {

    public static void GenerateDefaultMessage() {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    static void RecordMessage(String message) {

        String text = "";

        try 
        {
            text = URLDecoder.decode(message.split("=")[1], "ISO-8895-15");
        }
        catch (UnsupportedEncodingException ex)
        {
            ex.printStackTrace();
        }

        System.out.println(text);

        try
        {
            VoiceManager voiceManager = VoiceManager.getInstance();
            Voice helloVoice = voiceManager.getVoice("kevin16");

            String out_filename = SIPSpeaker.conf.message_wav.split(".wav")[0];
            SingleFileAudioPlayer out_audio = new SingleFileAudioPlayer(out_filename,AudioFileFormat.Type.WAVE);

            helloVoice.allocate();
            helloVoice.setAudioPlayer(out_audio);

            out_audio.begin(10000);
            helloVoice.speak(text);
            out_audio.drain();
            out_audio.close();
            helloVoice.deallocate();
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
        
    }

    public void PlayFileOnNet(String wavFileName,String senderIpAddress, String RtpPort) throws Exception {

        Format[] format = new Format[] { new AudioFormat(AudioFormat.GSM_RTP) };
        ContentDescriptor cd = new ContentDescriptor(ContentDescriptor.RAW_RTP);

        File mediaFile = new File(wavFileName);
        System.out.println("Transmitting file: "+wavFileName);
        DataSource ds = Manager.createDataSource(new MediaLocator(mediaFile.toURL()));

        MediaLocator mlr = new MediaLocator("rtp://"+senderIpAddress+":"+RtpPort+"/audio");
        Processor mediaProcessor = Manager.createRealizedProcessor(new ProcessorModel(ds,format,cd));
        DataSink datasink = Manager.createDataSink(mediaProcessor.getDataOutput(),mlr);

        mediaProcessor.start();

        double wavDuration = mediaProcessor.getDuration().getSeconds();
        System.out.println("Duration of wav file: "+wavDuration+"\r\n");

        datasink.open();
        datasink.start();
        Thread.sleep(500+1000*(int)wavDuration);
        
        datasink.stop();
        datasink.close();
        mediaProcessor.stop();
        mediaProcessor.close();
    }
}